package com.canbot.u05.activity.shoppingGuide.advisory;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.AdvisoryQA;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 咨询--设置问题界面
 */
public class SettingQuestionActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private final static String TAG = "SettingQuestionActivity";

        private final String AUDIO_SALE_DIR = PathConst.SHOPPING_GUIDE_DIR + "advisory/";

        private Button btnBack, btnSure;

        private EditText editText;

        private String question;

        private boolean isEdit;

        private Dialog dialogLoading;

        private AdvisoryQA advisoryQA;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_setting_question);

                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, AUDIO_SALE_DIR + "wtszyd_zxwd_u05_001.wav");
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }
                String js = getIntent().getStringExtra("data");
                if (!TextUtils.isEmpty(js)) {
                        isEdit = true;
                        Logger.e(TAG, "接收数据=" + js);
                        advisoryQA = JSON.parseObject(js, AdvisoryQA.class);
                }
                setViews();
        }


        private void setViews() {
                btnBack = (Button) findViewById(R.id.btn_back);
                btnSure = (Button) findViewById(R.id.btn_sure);
                btnBack.setOnClickListener(this);
                btnSure.setOnClickListener(this);
                editText = (EditText) findViewById(R.id.et_question);
                if (isEdit) {
                        editText.setText(advisoryQA.getQuestion());
                }
                editText.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                                if (isEdit) {
                                        advisoryQA.setQuestion(s.toString());
                                        Logger.e(TAG, "改变的问题=" + s.toString());
                                }
                        }
                });

                editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View v, boolean hasFocus) {
                                if (hasFocus) {
                                        editText.setSelection(editText.length());
                                }
                        }
                });
        }


        /**
         * 修改胸口的问题
         */
        private void editQuestionFromPad() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this,getString(R.string.data_upload));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                String values = JSON.toJSONString(advisoryQA);
                Logger.e(TAG, "上传数据" + values);
                Call<String> call = salesApi.editAdvisory(values);

                call.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                if (response.body() != null) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        String body = response.body();

                                        Logger.e(TAG, "网络返回的数据" + body + "");

                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                }
                                else {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                t.fillInStackTrace();
                                Logger.e(TAG, "网络返回的数据错误信息 " + call.toString());
                                ToastTools.newInstance(SettingQuestionActivity.this).showText(getString(R.string.submit_failure));
                        }
                });
        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.btn_back:
                                this.finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;
                        case R.id.btn_sure:
                                String question = editText.getText().toString().trim();
                                if (TextUtils.isEmpty(question)) {
                                        ToastTools.newInstance(SettingQuestionActivity.this).showText(getString(R.string.problem_cannot_empty));
                                        return;
                                }
                                if (isEdit) {
                                        editQuestionFromPad();
                                }
                                else {
                                        Intent intent = new Intent(this, EditActivity.class);
                                        intent.putExtra("question", question);
                                        startActivity(intent);
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                }
                                break;
                }
        }

        private static final int TIMEOUT = 100;//超时时间100s

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

        @Override
        protected void onDestroy() {
                isEdit = false;
                super.onDestroy();
        }
}
